/**
 * axios 请求
 */
import axios from "axios";
import { message } from "ant-design-vue";
import config from "~/config";

const MODE = import.meta.env.MODE; // 环境变量

import { userStore } from "../stores/modules/user";
import router from "../router";

function HttpRequest(url, params, method, path) {
  const store = userStore();
  const query = path === undefined ? "default" : path;
  const accessToken = store.userInfo.access_token || "";

  let httpDefault = {};
  //处理路径问题
  let base = config[MODE];

  if (method === "get") {
    httpDefault = {
      params: {
        ...params,
        platform: "pc",
        version: "1.0",
      },
      headers: {
        "Content-Type": "application/json; charset=utf-8;text/html",
        authorization: "Bearer " + accessToken,
      },
    };
  } else {
    httpDefault = {
      data: {
        ...params,
        platform: "pc",
        version: "1.0",
      },
      headers: {
        authorization: "Bearer " + accessToken,
      },
    };
  }
  //赋值完全部路径
  return axios({
    baseURL: base.apiBaseUrl, // 请求域名地址
    url,
    method,
    ...httpDefault,
  }).then((res) => {
    if (res.data.code === -2 && query !== "/login") {
      //清除token
      store.$reset();
      router.push({ path: "/login" });
      return;
    } else if (res.data.code === -3) {
      message.error(res.data.msg);
      //没有权限，先不处理
      // history.push('/exception/403');
      return;
    } else if (res.data.code === -1) {
      message.error(res.data.msg);
    } else if (res.data.code === -4) {
      message.error(res.data.msg);
      // router.push("/");
    }
    return res.data;
  });
}

export default HttpRequest;
